package pattern.behavior.resChain;

import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class ResChainApplicationRunner implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        boolean pass = true;
        for (AbstractHandler handler : getAllHandler()) {
            pass = handler.doHandle();
            System.out.println("执行的策略是："+ handler.getClass().getSimpleName());
        }
        System.out.println("是否通过：" + pass);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    private List<AbstractHandler> getAllHandler() {
        return applicationContext.getBeansOfType(AbstractHandler.class)
                .entrySet().stream()
                .sorted(Map.Entry.comparingByKey(
                        (name1,name2) -> {
                            int order1 = Objects.requireNonNull(applicationContext.findAnnotationOnBean(name1, Order.class)).value();
                            int order2 = Objects.requireNonNull(applicationContext.findAnnotationOnBean(name2, Order.class)).value();
                            return order1-order2;
                        }
                ))
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
    }
}
